package com.android.manghe.market.view.sku;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.StyleRes;

import com.android.base.tools.Glide.GlideHelper;
import com.android.base.tools.ScreenUtil;
import com.android.manghe.R;
import com.android.manghe.market.model.Product;
import com.wuhenzhizao.sku.bean.Sku;
import com.wuhenzhizao.sku.bean.SkuAttribute;
import com.wuhenzhizao.sku.view.OnSkuListener;
import com.wuhenzhizao.sku.view.SkuSelectScrollView;

import java.util.List;

/**
 * Created by liufei on 2017/11/30.
 */
public class ProductSkuDialog extends Dialog {
    private Context context;
    private Product product;
    private List<Sku> skuList;
    private Callback callback;

    private Sku selectedSku;
    private String priceFormat;
    private String stockQuantityFormat;

    public ProductSkuDialog(@NonNull Context context) {
        this(context, R.style.CommonBottomDialogStyle);
    }

    private ProductSkuDialog(@NonNull Context context, @StyleRes int themeResId) {
        super(context, themeResId);
        this.context = context;
        initView();
    }

    private View ibSkuClose;
    private TextView btnSubmit, tvSkuInfo,
            tvSkuSellingPrice, tvSkuQuantity;
    private SkuSelectScrollView scrollSkuList;
    private ImageView ivSkuLogo;

    private void initView() {
        View rootView = LayoutInflater.from(this.context).inflate(R.layout.dialog_product_sku, null, false);
        setContentView(rootView);
        rootView.findViewById(R.id.contentView).setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) (ScreenUtil.getScreenHeight(context) * 0.8)));

        ibSkuClose = rootView.findViewById(R.id.ib_sku_close);
        scrollSkuList = rootView.findViewById(R.id.scroll_sku_list);
        btnSubmit = rootView.findViewById(R.id.btn_submit);
        tvSkuInfo = rootView.findViewById(R.id.tv_sku_info);
        ivSkuLogo = rootView.findViewById(R.id.iv_sku_logo);
        tvSkuSellingPrice = rootView.findViewById(R.id.tv_sku_selling_price);
        tvSkuQuantity = rootView.findViewById(R.id.tv_sku_quantity);
        scrollSkuList.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        ibSkuClose.setOnClickListener(v -> dismiss());

        scrollSkuList.setListener(new OnSkuListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onUnselected(SkuAttribute unselectedAttribute) {
                selectedSku = null;
                GlideHelper.loadCropRoundTrans(context, product.getMainImage(), ivSkuLogo, 8);
                String firstUnselectedAttributeName = scrollSkuList.getFirstUnelectedAttributeName();
                tvSkuInfo.setText(String.format("请选择：%s", firstUnselectedAttributeName));
                tvSkuSellingPrice.setText(String.format(priceFormat, product.getSellingPrice()));
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onSelect(SkuAttribute selectAttribute) {
                String firstUnselectedAttributeName = scrollSkuList.getFirstUnelectedAttributeName();
                tvSkuInfo.setText("请选择：" + firstUnselectedAttributeName);
                tvSkuSellingPrice.setText(String.format(priceFormat, product.getSellingPrice()));
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onSkuSelected(Sku sku) {
                selectedSku = sku;
                GlideHelper.loadCropRoundTrans(context, selectedSku.getMainImage(), ivSkuLogo, 8);
                List<SkuAttribute> attributeList = selectedSku.getAttributes();
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < attributeList.size(); i++) {
                    if (i != 0) {
                        builder.append("　");
                    }
                    SkuAttribute attribute = attributeList.get(i);
                    builder.append("\"" + attribute.getValue() + "\"");
                }
                tvSkuInfo.setText("已选：" + builder.toString());
                tvSkuSellingPrice.setText(String.format(priceFormat, sku.getSellingPrice()));
            }
        });
        btnSubmit.setOnClickListener(v -> {
            int quantityInt = scrollSkuList.getSelectedQuantity();
            if(selectedSku == null){
                Toast.makeText(getContext(), tvSkuInfo.getText(), Toast.LENGTH_SHORT).show();
                return;
            }
            if (quantityInt > 0 && quantityInt <= selectedSku.getStockQuantity()) {
                if (TextUtils.isEmpty(scrollSkuList.getFirstUnelectedAttributeName())) {
                    callback.onAdded(selectedSku, quantityInt);
                    dismiss();
                } else {
                    Toast.makeText(getContext(), "请选择商品属性", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(getContext(), "商品数量超出库存，请修改数量", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void setData(Product product, Callback callback) {
        this.product = product;
        this.skuList = product.getSkus();
        this.callback = callback;

        priceFormat = "¥ %s";
        stockQuantityFormat = "库存:%1$s";

        updateSkuData();
        scrollSkuList.updateQuantityOperator(1);
    }

    @SuppressLint("SetTextI18n")
    private void updateSkuData() {
        scrollSkuList.setSkuList(product.getSkus());

        Sku firstSku = product.getSkus().get(0);
        if (firstSku.getStockQuantity() > 0) {
            selectedSku = firstSku;
            // 选中第一个sku
            scrollSkuList.setSelectedSku(selectedSku);

            GlideHelper.loadCropRoundTrans(context, selectedSku.getMainImage(), ivSkuLogo, 8);
            tvSkuSellingPrice.setText(String.format(priceFormat, firstSku.getSellingPrice()));
            List<SkuAttribute> attributeList = selectedSku.getAttributes();
            tvSkuQuantity.setVisibility(View.VISIBLE);
            tvSkuQuantity.setText(String.format(stockQuantityFormat, selectedSku.getStockQuantity()));
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < attributeList.size(); i++) {
                if (i != 0) {
                    builder.append(" ");
                }
                SkuAttribute attribute = attributeList.get(i);
                builder.append("\"" + attribute.getValue() + "\"");
            }
            tvSkuInfo.setText("已选：" + builder.toString());
        } else {
            GlideHelper.loadCropRoundTrans(context, product.getMainImage(), ivSkuLogo, 8);
            tvSkuSellingPrice.setText(String.format(priceFormat, firstSku.getSellingPrice()));
            tvSkuQuantity.setVisibility(View.INVISIBLE);
            tvSkuInfo.setText("请选择：" + skuList.get(0).getAttributes().get(0).getKey());
        }
    }

    public interface Callback {
        void onAdded(Sku sku, int quantity);
    }
}
